import sqlite3, datetime
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *

def student_view(request, student_id):
	student_id = to_int(student_id)
	initialize(request)
	output = ""
	title = t("View student")
	
	if not (request.session["rights"]["edit_students"] or (request.session["user"]["type"] == 1 and request.session["user"]["id"] == student_id)):
		output += '<p class="error_message">'+t('You do not have the rights to edit students.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    
		
		
		result = sql_cursor.execute("""select first_name, middle_name, last_name, phone_0, phone_1, email, active from students where id = ?""", (student_id,)).fetchone()
		
		if result == None:
			output += '<p class="error_message">'+t('Student does not exist.')+'</p>'
		else:
			first_name, middle_name, last_name, phone_0, phone_1, email, active = result
			name = display_name(first_name, middle_name, last_name)
			title = name
			
			output += '<div class="row"><div class="col-xs-12 col-md-6">'
			
			if 'delete' in request.POST.keys():
				if not request.session["rights"]["edit_credit"]:
					output += '<p class="error_message">'+t('You do not have the rights to add or remove credit.')+'</p>'
				else:
					sql_cursor.execute("""delete from student_credit where id = ?""", (request.POST["delete"],))
					sql_connection.commit()
					
			if 'credit' in request.POST.keys():
				if not request.session["rights"]["edit_credit"]:
					output += '<p class="error_message">'+t('You do not have the rights to add or remove credit.')+'</p>'
				else:
					values = (request.POST["student_class_id"], max(0, float(request.POST["credit"]))*60*60, request.POST["paid"], request.session["user"]["id"], int(time.time()), request.POST["note"])
					sql_cursor.execute("""INSERT INTO student_credit ('student_class_id', 'credit', paid, 'staff_id', 'time', 'note') VALUES (?, ?, ?, ?, ?, ?)""", values)
					sql_connection.commit()
						
			if request.session["rights"]["edit_students"]:
				output += ('<h3>'+t('General information')+'</h3>'
				'<table class="table viewuser table-striped table-hover">'
				'<tr><td>'+t('Name')+'</td><td>'+name+'</td></tr>'
				'<tr><td>'+t('Phone 1')+'</td><td>'+phone_0+'</td></tr>'
				'<tr><td>'+t('Phone 2')+'</td><td>'+phone_1+'</td></tr>'
				'<tr><td>'+t('Email')+'</td><td>'+email+'</td></tr>'
				'<tr><td>'+t('Active')+'</td><td>'+(t("Yes", (), True) if active == 1 else t("No", (), True))+'</td></tr>'
				'</table>'
				)
			
			classes = {}
			db_rows = sql_cursor.execute("""SELECT id, class_id, (select (select first_name from staff where id = classes.teacher_id) from classes where id = class_id), (select subject from classes where id = class_id), (select description from classes where id = class_id), start_time, end_time FROM student_classes where student_id = ?""", (student_id,))
			for id, class_id, teacher_name, subject, description, start_time, end_time in db_rows:
				classes[class_id] = {"student_class_id": id, "start_time": start_time, "end_time": end_time, "teacher_name": teacher_name, "subject": subject, "description": description, "credit": 0, "posts": []}
			
			output += '<br /><h3>'+t('Feedback received')+'</h3>'
			db_rows = sql_cursor.execute("""select comment, time, (select start_time from lessons where lessons.id = lesson_id), (select class_id from lessons where lessons.id = lesson_id), on_time, did_homework from student_feedback where student_id = ? order by time desc""", (student_id, ))
			no_comments = True
			for comment, feedback_time, lesson_time, class_id, on_time, did_homework in db_rows:
				teacher_name = classes[class_id]["teacher_name"]
				output += '<div class="alert alert-warning alert-dismissible"><b>'+t('Lesson time:')+' '+stamp_to_display(lesson_time, "date_time_format")+' - '+t('Feedback time:')+' '+stamp_to_display(feedback_time, "date_time_format")+'</b><br />'+("" if teacher_name == None else classes[class_id]["teacher_name"]+': ')+comment + '<br /><br />'+t('Did homework: <b>%s</b>, One time: <b>%s</b>', ((t("yes", (), True) if on_time == 1 else t("no", (), True)), (t("Yes", (), True) if did_homework == 1 else t("no", (), True))))+'</b></div>'
			if no_comments:
				output += t('No feedback received yet.')
			
			output += '</div><div class="col-xs-12 col-md-6"><h3>'+t('Class Credits')+'</h3>'
			
			for class_id in classes:
				db_rows = sql_cursor.execute("""select id, credit, paid, (select first_name from staff where id = staff_id), time, note from student_credit where student_class_id = ?""", (classes[class_id]["student_class_id"],))
				for id, credit, paid, staff_name, timestamp, note in db_rows:
					classes[class_id]["credit"] += credit
					classes[class_id]["posts"].append({"time": timestamp, "description": (t('Parents paid: %sRMB', (str(paid)))+' '+note if request.session["user"]["type"] == 0 else t("Credit added")), "credit": credit, "user": staff_name, "id": id})
					
			
				db_rows = sql_cursor.execute("""select id, start_time, end_time from lessons where class_id = ? order by start_time desc""", (class_id,))
				for lesson_id, start_time, end_time  in db_rows:
					if start_time > classes[class_id]["start_time"] and (end_time < classes[class_id]["end_time"] or classes[class_id]["end_time"] == -1):
						classes[class_id]["credit"] -= end_time - start_time
						classes[class_id]["posts"].append({"time": start_time, "description": '<a href="/office/student-schedule/'+str(student_id)+'/'+str(stamp_to_week(start_time))+'/">'+(t('Lesson Complete') if start_time < time.time() - global_vars["timezone_offset"] else t('Upcoming lesson'))+'</a>', "credit": -end_time + start_time, "user":"", "id": -1})
			
			from_time = time.time()
			
			for id in classes:
				class_name = class_subjects[classes[id]['subject']]+' - '+classes[id]['description']+' - '+classes[id]['teacher_name']
				output += '<h4><a href="/office/class-edit/'+str(id)+'/"><b>'+class_name+'</b></a></h4>'
				
				if request.session["user"]["type"] == 0:
					output += '<table class="table"><tr><th>'+t('Time')+'</th><th>'+t('User')+'</th><th>'+t('Description')+'</th><th>'+t('Amount')+'</th><th></th></tr>'
				else:
					output += '<table class="table"><tr><th>'+t('Time')+'</th><th>'+t('Description')+'</th><th>'+t('Amount')+'</th><th></th></tr>'
				
				for pos in classes[id]["posts"]:
					from_time = pos["time"]
					output += '<tr><td>'+stamp_to_display(from_time, "date_time_format")+'</td>'+('<td>'+pos["user"]+'</td>' if request.session["user"]["type"] == 0 else '')+'<td>'+pos["description"]+'</td><td><p style="color: '+('green' if pos["credit"] >= 0 else 'red')+';">'+str(pos["credit"]/float(60*60))+'</p></td><td>'+('<a href="#" onclick="confirm_delete('+str(pos["id"])+')">'+version["icons"]["delete"]+'</a>' if pos["id"] != -1 else '')+'</td></tr>'
				output += (
				'<tr><td> </td><td> </td>'+('<td> </td>' if request.session["user"]["type"] == 0 else '')+'<td> </td><td> </td></tr>'
				'<tr><td><b>'+t('Sum')+'</b></td><td>'+('<td> </td>' if request.session["user"]["type"] == 0 else '')+'</td><td>'+str(classes[id]["credit"]/float(60*60))+'</td><td> </td></tr>'
				)
				output += '</table><br /><br />'
			
				if request.session["rights"]["edit_credit"]:
					output += (
					'<b>'+t('Add credit to student class: %s', class_name)+'</b>'
					'<form action="?" method="post">'
					'<table class="table">'
					'<tr><td>'+t('Credit:')+'</td><td><input type="text" name="credit">'+t(' (in hours)')+'</td></tr>'
					'<tr><td>'+t('Total paid:')+'</td><td><input type="text" name="paid">'+t(' (in RMB)')+'</td></tr>'
					'<tr><td>'+t('Note:')+'</td><td><input type="text" name="note"></td></tr>'
					'<tr><td></td><td><input type="submit" value="'+t('Add credit')+'" class="btn btn-primary"></td></tr>'
					'<input type="hidden" name="student_class_id" value="'+str(classes[id]["student_class_id"])+'">'
					'</table></form>'
					'<br /><br />'
					)
			output += """
			</div></div><script>
			function confirm_delete(id){
				var retVal = confirm('"""+t('Are you sure you want to remove this credit entry?')+"""');
				if( retVal == true ){
					post_request({"delete": id});
					return true;
				}
			}
			</script>
			"""
	return format_response(version["icons"]["students"]+title, output)
	
def student_edit(request, student_id):
	student_id = to_int(student_id)
	initialize(request)
	output = ""
	
	has_rights = request.session["rights"]["edit_students"] or (request.session["user"]["type"] == 1 and request.session["user"]["id"] == student_id)
	if not has_rights:
		output += '<p class="error_message">'+t('You do not have the rights to edit students.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		result = sql_cursor.execute("""select first_name, last_name, phone_0, phone_1, email, city, street_address, postal_code, active from students where id = ?""", (student_id,)).fetchone()
		
		if result == None:
			output += '<div class="col-xs-12"><p class="bg-warning">'+t('Student does not exist</p>')+'</div>'
		else:
			
			if 'reset' in request.POST.keys():
				output += reset_user_password(1, student_id, result[4])
				
			if 'email' in request.POST.keys():
				active = int(request.POST.get("active", 0))
				values = (request.POST["first_name"], request.POST["last_name"], request.POST["phone_0"], request.POST["phone_1"], request.POST["email"], request.POST["city"], request.POST["street_address"], to_int(request.POST["postal_code"]), to_int(active), to_int(student_id))
				sql_cursor.execute("""Update students set first_name = ?, last_name = ?, phone_0 = ?, phone_1 = ?, email = ?, city = ?, street_address = ?, postal_code = ?, active = ? where id = ?""", values)
				sql_connection.commit()
				output += '<p class="bg-success">'+t("User infomation updated")+'</p>'
				result = sql_cursor.execute("""select first_name, last_name, phone_0, phone_1, email, city, street_address, postal_code, active from students where id = ?""", (student_id,)).fetchone()

			if 'current_password' in request.POST.keys():
				if not test_password(result[4], request.POST["current_password"], 1):
					output += '<p class="bg-warning">'+t('Wrong password')+'</p>'
				elif request.POST["password1"] != request.POST["password2"]:
					output += '<p class="bg-warning">'+t('Passwords don\'t match')+'</p>'
				else:
					salt = random_hex()
					pass_hash = pass_derivation(request.POST["password1"], salt)
					sql_cursor.execute("""update students set pass_hash = ?, pass_salt = ? where id = ?""", (pass_hash, salt, student_id))
					sql_connection.commit()
					output += '<p class="bg-success">'+t('Password changed.')+'</p>'
				
			output += (
			'<div class="row"><div class="col-xs-12 col-md-6">'
			'<h3>'+t('Edit Student Details')+'</h3>'
			'<form action="?" method="POST">'
			'<table class="table newuser">'
			'<tr><td>'+t('First name')+'</td><td><input type="text" name="first_name" value="'+result[0]+'"></td></tr>'
			'<tr><td>'+t('Last name')+'</td><td><input type="text" name="last_name" value="'+result[1]+'"></td></tr>'
			'<tr><td>'+t('Phone number 1')+'</td><td><input type="text" name="phone_0" value="'+result[2]+'"></td></tr>'
			'<tr><td>'+t('Phone number 2')+'</td><td><input type="text" name="phone_1" value="'+result[3]+'"></td></tr>'
			'<tr><td>'+t('Email')+'</td><td><input type="text" name="email" value="'+result[4]+'"></td></tr>'
			'<tr><td>'+t('City')+'</td><td><input type="text" name="city" value="'+result[5]+'"></td></tr>'
			'<tr><td>'+t('Street address')+'</td><td><input type="text" name="street_address" value="'+result[6]+'"></td></tr>'
			'<tr><td>'+t('Postal code')+'</td><td><input type="text" name="postal_code" value="'+str(result[7])+'"></td></tr>'
			'<tr><td>'+t('Active')+'</td><td><input name="active" type="checkbox" value="1" '+("checked" if result[8] == 1 else "")+'></td></tr>'
			'<tr><td></td><td><input class="btn btn-primary"  type="submit" value="'+t('Edit')+'"></td></tr>'
			'</table>'
			'</form>'
            '</div>'
			)
			
			if (request.session["user"]["id"] != student_id):
				output += (
				'<div class="col-xs-12 col-md-6">'
				'<h3>'+t('Reset password')+'</h3>'
				'<p style="text-align: center;"><a class="btn btn-primary" role="button" href="#" onclick="confirm_reset_password('+str(student_id)+', \''+result[0]+'\')">'+t('Reset Password')+'</a></p>'
				)
			else:
				output += (
					'<div class="col-xs-12 col-md-6">'
					'<h3>'+t('Change Password')+'</h3>'
					'<form action="?" method="post" name="new_pass" id="new_pass">'
					'<table class="table newuser">'
					'<tr><td>'+t('Current Password')+'</td><td><input type="password" name="current_password"></td></tr>'
					'<tr><td>'+t('New Password')+'</td><td><input type="password" id="password1" name="password1" onkeyup="pass_str(document.forms.new_pass.password1.value);pass_mtc(document.forms.new_pass.password1.value, document.forms.new_pass.password2.value);"/><br /><div id="verdict" style="display: block;"></div></td></tr>'
					'<tr><td>'+t('Repeat New Password')+'</td><td><input type="password" id="password2" name="password2" onkeyup="pass_mtc(document.forms.new_pass.password1.value, document.forms.new_pass.password2.value)" /><br /><br /><div id="match" style="display: block;"></div></td></tr>'
					'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Change')+'"></td></tr>'
					'</table>'
					'</form>'
				)

			
			output += """
			<script>
				function confirm_reset_password(id, name){
					var retVal = confirm('"""+t('Are you sure you want to reset the password of %%s?')+"""'.replace("%s", name));
					if( retVal == true ){
						post_request({"reset": id}, "/office/student-edit/"+id+"/");
						return true;
					}
				}
				function pass_str(pass){
					vericts = [
						"<img src='/static/icons/bad.png' /> <b  class='error'>Too weak</b>", 
						"<img src='/static/icons/good.png' /> <b style='color:#742400;display: inline;'>"""+t('Weak')+"""</b>",
						"<img src='/static/icons/good.png' /> <b style='color:#494900;display: inline;'>"""+t('Mediocre')+"""</b>",
						"<img src='/static/icons/good.png' /> <b style='color:#247400;display: inline;'>"""+t('Strong')+"""</b>",
						"<img src='/static/icons/good.png' /> <b style='color:#009900;display: inline;'>"""+t('Very strong')+"""</b>",
					];
					document.getElementById('verdict').innerHTML = vericts[password_strength(pass)];
				}
				function pass_mtc(pass1, pass2){
					document.getElementById('match').innerHTML =  (password_match(pass1, pass2) ? '<img src="/static/icons/good.png" /> <b style="color:#009900;display: inline;">"""+t('Passwords match')+"""</b>' : "<img src='/static/icons/bad.png' /> <b class='error'>"""+t("Passwords don't match")+"""</b>");
				}
			</script>
			</div>
			</div>
			"""
		
	return format_response(version["icons"]["students"]+t("Edit Student"), output)

def student_overview(request):
	initialize(request)
	output = ""
	if not request.session["rights"]["view_students"]:
		output += '<p class="error_message">'+t('You do not have the rights to view students.')+'</p>'
	else:

		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		if 'delete' in request.POST.keys():
			if not request.session["rights"]["delete_students"]:
				output += '<p class="error_message">'+t('You do not have the rights to delete students')+'.</p>'
			else:
				result = sql_cursor.execute("""select first_name, last_name from students where id = ?""", (request.POST["delete"],)).fetchone()
				log_message(sql_cursor, t("Student deleted (%s)", display_name(result[0],"",result[1])))
				sql_cursor.execute("""delete from student_feedback where student_id = ?""", (request.POST["delete"],))
				sql_cursor.execute("""delete from students where id = ?""", (request.POST["delete"],))
				sql_cursor.execute("""delete from student_classes where student_id = ?""", (request.POST["delete"],))
				sql_connection.commit()
				output += '<p class="bg-success">'+t('Student %s deleted', (display_name(result[0],"",result[1])))+'</p>'

		if 'active' in request.POST.keys():
			sql_cursor.execute("""update students set active = ? where id = ?""", (request.POST["active"], request.POST["id"]))
			if int(request.POST["active"]) == 0:
				sql_cursor.execute("""update student_classes set end_time = ? where student_id = ?""", (time.time(), request.POST["id"]))
			sql_connection.commit()
			
		if 'email' in request.POST.keys():
			values = (
				request.POST.get('first_name', ''),
				request.POST.get('middle_name', ''),
				request.POST.get('last_name', ''),
				request.POST.get('phone_0', ''),
				request.POST.get('phone_1', ''),
				request.POST.get('city', ''),
				request.POST.get('street_address', ''),
				to_int(request.POST.get('postal_code', 0)),
				request.POST.get('email', ''),
			)

			sql_cursor.execute("""INSERT INTO students ('first_name', 'middle_name', 'last_name', 'phone_0', 'phone_1', 'city', 'street_address', 'postal_code', 'email') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", values)
			sql_connection.commit()
			output += '<p class="bg-success">'+t('New student created')+'</p>'
		
		output += '<div class="row"><div class="col-xs-12 col-md-6"><h3>'+t('Current Students')+'</h3><table class="table viewuser table-striped table-hover"><tr><th style="text-align:left"><b>'+t('Name')+'</b></th><th style="text-align: right;"></th></tr>'
		
		if request.session['show_disabled']:
			db_rows = sql_cursor.execute("""SELECT id, first_name, middle_name, last_name, active FROM students order by active desc""")
		else:
			db_rows = sql_cursor.execute("""SELECT id, first_name, middle_name, last_name, active FROM students where active = 1""")
		
		for id, first_name, middle_name, last_name, active in db_rows:
			name = display_name(first_name, middle_name, last_name)
			output += '<tr'+('' if active else ' class="disabled_row"')+'><td>'+name+'</td><td style="text-align:right">'
			output += '<a href="/office/student-schedule/'+str(id)+'/">'+version["icons"]["schedule2"]+'</a>'

			if request.session["rights"]["edit_students"]:
				output += '<a href="/office/student-view/'+str(id)+'/">'+version["icons"]["info"]+'</a>'
				output += '<a href="/office/student-edit/'+str(id)+'/">'+version["icons"]["edit"]+'</a>'
				output += '<a href="#" onclick="post_request({\'active\': '+str(1 - active)+', \'id\': '+str(id)+'});">'+(version["icons"]["enable"] if int(active) == 0 else version["icons"]["disable"])+'</a>'
			
			if request.session["rights"]["edit_students"]:
				output += '<a href="#" onclick="confirm_delete(\''+str(id)+'\', \''+name+'\')">'+version["icons"]["delete"]+'</a>'
			output += '</td></tr>'
		output += '</table><button class="btn btn-primary" style="display: inline; margin-top: 10px; float: right;" type="submit" onclick="post_request({\'show_disabled\': '+str(1 - int(request.session['show_disabled']))+'});">'+(t('Hide disabled', (), True) if request.session['show_disabled'] else t('Show disabled', (), True))+'</button>'        

		if request.session["rights"]["edit_students"]:
			output += (
			'</div>'
			'<div class="col-xs-12 col-md-6">'
			'<form action="?" method="POST" name="account">'
			'<h3>'+t('Create New Student')+'</h3>'
			'<table class="table newuser">'
			'<tr><td>'+t('First name: ')+'</td><td><input type="text" name="first_name"></td></tr>'
			'<tr><td>'+t('Last name: ')+'</td><td><input type="text" name="last_name"></td></tr>'
			'<tr><td>'+t('Phone number 1: ')+'</td><td><input type="text" name="phone_0"></td></tr>'
			'<tr><td>'+t('Phone number 2: ')+'</td><td><input type="text" name="phone_1"></td></tr>'
			'<tr><td>'+t('Email: ')+'</td><td><input type="text" name="email" onkeyup="update_email(document.forms.account.email.value)"/><br /><div id="email" style="display: inline;"></div></td></td></tr>'
			'<tr><td>'+t('City: ')+'</td><td><input type="text" name="city"></td></tr>'
			'<tr><td>'+t('Street address: ')+'</td><td><input type="text" name="street_address"></td></tr>'
			'<tr><td>'+t('Postal code: ')+'</td><td><input type="text" name="postal_code"></td></tr>'
			'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Create')+'"></td></tr>'
			'</table>'
			'</form>')
			output += """
			<script>
				function confirm_delete(id, name){
					var retVal = confirm('"""+t('Are you sure you want to delete student %%s?')+"""'.replace("%s", name));
					if( retVal == true ){
						post_request({"delete": id}, "/office/student-overview/");
						return true;
					}
				}
				function update_email(email){
					if(validate_email(email)){
						document.getElementById('email').innerHTML = '<img src="/static/icons/good.png" /> """+t('Valid email')+"""';
					}else{
						document.getElementById('email').innerHTML = '<img src="/static/icons/bad.png" /> """+t('Invalid email')+"""';
					}
				}
			</script>
			"""
		
		output += '</div></div>'  
    
	return format_response(version["icons"]["students"]+t("Student Overview"), output)
	
def student_schedule(request, student_id, selected_week):	
	initialize(request)
	output = ""

	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()    
	
	header = ""

	result = sql_cursor.execute("""select first_name, last_name from students where id = ?""", (student_id,)).fetchone()
	if result == None:
		output += '<div class="col-xs-12"><p class="bg-warning">'+t('Student does not exist')+'</p></div>'
	else:
		output += schedule_edit()

		request.session['schedule_week'] = int(selected_week) if selected_week != None else request.session['schedule_week']
		
		schedule = {0:{},1:{},2:{}}
		
		# Lesson schedule
		classes = {}
		db_rows = sql_cursor.execute("""select id, class_id, (select subject from classes where id = class_id), (select description from classes where id = class_id), (select edit_mode from classes where id = class_id), (select teacher_id from classes where id = class_id), (select first_name from staff where id = (select teacher_id from classes where id = class_id)), start_time, end_time, (select active from classes where classes.id = class_id) from student_classes where student_id = ? and (select active from classes where classes.id = class_id) = 1""", (student_id,))
		for student_class_id, class_id, subject, description, edit_mode, teacher_id, teacher_name, start_time, end_time, active in db_rows:
			classes[class_id] = {"student_class_id": student_class_id, "description": class_subjects[subject]+" - "+description, "can_edit": int(edit_mode) * int(active), "teacher_id": teacher_id, "teacher_name": teacher_name, "credit": 0, "start_time": start_time, "end_time": end_time}
		
		for class_id in classes:
			db_rows = sql_cursor.execute("""select credit from student_credit where student_class_id = ?""", (classes[class_id]["student_class_id"],))
			for row in db_rows:
				classes[class_id]["credit"] += row[0]
			
			print "Class time", classes[class_id]["start_time"], classes[class_id]["end_time"]
			if classes[class_id]["end_time"] == -1:
				db_rows = sql_cursor.execute("""select id, start_time, end_time from lessons where class_id = ? order by start_time desc""", (class_id, ))
			else:
				db_rows = sql_cursor.execute("""select id, start_time, end_time from lessons where class_id = ? and start_time > ? and start_time < ? order by start_time desc""", (class_id, classes[class_id]["start_time"], classes[class_id]["end_time"]))
			for lesson_id, start_time, end_time  in db_rows:
				print "Lesson",start_time, end_time
				if start_time > classes[class_id]["start_time"] and (end_time < classes[class_id]["end_time"] or classes[class_id]["end_time"] == -1):
					classes[class_id]["credit"] -= end_time - start_time
		
		i = 0
		for key, class_values in classes.iteritems():
			# Default schedule
			db_rows = sql_cursor.execute("""SELECT start_time, end_time, status FROM teacher_default_schedule where teacher_id = ?""", (class_values["teacher_id"],))
			for row in db_rows:
				schedule[0][i] = {"id": str(i), "start_time": row[0], "end_time": row[1], "type": row[2], "editable": 0, "layer": class_values["teacher_id"]}
				i += 1

			# Weekly schedule
			week_sum = 0
			db_rows = sql_cursor.execute("""SELECT id, start_time, end_time, status FROM teacher_schedule where teacher_id = ? and start_time >= ? and end_time <= ?""", (class_values["teacher_id"], week_to_stamp(request.session['schedule_week']), week_to_stamp(request.session['schedule_week']+1)))
			for row in db_rows:
				schedule[1][row[0]] = {"id": row[0], "start_time": row[1] - week_to_stamp(request.session['schedule_week']), "end_time": row[2] - week_to_stamp(request.session['schedule_week']), "type": row[3], "editable": 0, "layer": class_values["teacher_id"]}
			
			# Teacher busy time
			teacher_classes = []
			db_rows = sql_cursor.execute("""select id from classes where teacher_id = ?""", (class_values["teacher_id"],))
			for row in db_rows:
				teacher_classes.append(row[0])
			
			for teacher_class in teacher_classes:
				db_rows = sql_cursor.execute("""select start_time, end_time, id from lessons where class_id = ? and start_time >= ? and end_time <= ?""", (teacher_class, week_to_stamp(request.session['schedule_week']), week_to_stamp(request.session['schedule_week']+1)))
				for start_time, end_time, id in db_rows:
					schedule[2][id] = {"id": id, "start_time": start_time - week_to_stamp(request.session['schedule_week']), "end_time": end_time - week_to_stamp(request.session['schedule_week']), "type": 5, "editable": 0, "layer": class_values["teacher_id"]}
				
		lessons = {}
		for student_class, class_vars in classes.iteritems():
			db_rows = sql_cursor.execute("""select start_time, end_time, (select teacher_id from classes where id = lessons.class_id), id, lessons.room_id, (select subject from classes where id = lessons.class_id), (select first_name from staff where id = (select teacher_id from classes where id = lessons.class_id)), class_id, confirmed, (select id from pending_confirmations where lesson_id = lessons.id and pending_confirmer_id = ? and pending_confirmer_type = 1) from lessons where class_id = ? and start_time >= ? and end_time <= ?""", (student_id, student_class, week_to_stamp(request.session['schedule_week']), week_to_stamp(request.session['schedule_week']+1)))
			for start_time, end_time, teacher_id, lesson_id, room_id, subject_id, teacher_name, class_id, confirmed, pending_confirmations in db_rows:
				if class_vars['end_time'] == -1 or (class_vars['start_time'] < start_time and class_vars['end_time'] > end_time):
					type = (3 if confirmed == 1 else 4)
					can_confirm = request.session["rights"]["edit_staff"] or (int(student_id) == request.session["user"]["id"] and class_id != None)
					schedule[2][lesson_id] = {"id": lesson_id, "start_time": start_time - week_to_stamp(request.session['schedule_week']), "end_time": end_time - week_to_stamp(request.session['schedule_week']), "type": type, "editable": 1, "layer": -1}
					lessons[lesson_id] = {"id":lesson_id, "room_id":room_id, "subject_id": subject_id, "teacher_name":teacher_name, "class_id":class_id, "can_confirm": can_confirm}
		
		for id, value in classes.iteritems():
			student_names = []
			db_rows = sql_cursor.execute("""select (select first_name from students where id = student_id) from student_classes where class_id = ?""", (id,))
			for row in db_rows:
				student_names.append(row[0])
			classes[id]["students"] = ', '.join(student_names[:2]) + ("..." if len(student_names) > 2 else "")
		
		rooms = {}
		db_rows = sql_cursor.execute("""SELECT id, name FROM classrooms""")
		for row in db_rows:
			rooms[row[0]] = {"name": row[1], "unavailable": {}}
		
		header = t('Schedule for %s', display_name(result[0],"",result[1]))
		
		if request.session["user"]["type"] == 1 and int(student_id) == request.session["user"]["id"]:
			view = 4
		else:
			view = 0
			
		output += schedule_html(view, schedule, "/office/student-schedule/"+student_id, lessons, rooms, classes)

	return format_response(version["icons"]["students"]+header, output)
